<template>
    <div class="global-search-container">
        <el-form :inline="true" :model="form" class="demo-form-inline">
            <el-form-item label="机构" v-show="!onlySlot && orgList.length > 1">
                <el-select v-model="form.orgId" filterable class="mechanism" @change="setDepartmentList">
                    <el-option
                        v-for="item in orgList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="科室" v-show="!onlySlot && showDep">
                <el-cascader
                    ref="cascaderSelector"
                    :key="isResouceShow"
                    class="dep-select"
                    v-model="form.dep"
                    :show-all-levels="false"
                    :options="departmentList"
                    :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
                    filterable>
                </el-cascader>
            </el-form-item>
            <el-form-item label="时间" v-show="!onlySlot && showTime" class="time-select-form-box">
                <el-select v-model="form.timeUnit" class="time-unit" placeholder="">
                    <el-option label="年" value="year"></el-option>
                    <el-option label="季度" value="quarter"></el-option>
                    <el-option label="月" value="month"></el-option>
                </el-select>
                <select-year v-show="form.timeUnit !== 'month'" @selectYear="selectYear" :yearMonth="form.yearMonth" />
                <el-date-picker
                    v-show="form.timeUnit === 'month'"
                    class="year-month"
                    v-model="form.yearMonth"
                    :type="form.timeUnit === 'month' ? 'month' : 'year'"
                    value-format="yyyy-MM-dd"
                    popper-class="custom-date-width"
                    :clearable="false">
                </el-date-picker>
                <el-select v-if="form.timeUnit === 'quarter'" class="quarter" v-model="form.quarter" placeholder="">
                    <el-option label="第一季度" value="1"></el-option>
                    <el-option label="第二季度" value="2"></el-option>
                    <el-option label="第三季度" value="3"></el-option>
                    <el-option label="第四季度" value="4"></el-option>
                </el-select>
            </el-form-item>
            <slot name="other-form"></slot>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
        </el-form>
        <div class="tool-box">
            <slot name="tool-box"></slot>
        </div>
    </div>
</template>

<script>
    import SelectYear from '@/components/SelectYear'

    export default {
        name: 'index',
        props: {
            // 不要自带的条件，全部由父组件传入
            onlySlot: {
                type: Boolean,
                default: false
            },
            // 不显示科室
            showDep: {
                type: Boolean,
                default: true
            },
            // 不显示时间
            showTime: {
                type: Boolean,
                default: true
            }
        },
        data () {
            return {
                // 搜索框
                form: {
                    orgId: '',
                    dep: '',
                    timeUnit: 'year',
                    yearMonth: '',
                    quarter: '1'
                },
                // 全局使用到的内容
                globalForm: {
                    orgId: '',
                    department: '',
                    depName: '',
                    start: '',
                    end: ''
                },
                // 机构列表
                orgList: [],
                // 科室列表
                departmentList: [],
                // cascader的key值，避免组件报错
                isResouceShow: 0
            }
        },
        created () {
            this.initData()
            this.setDepartmentList(this.form.orgId, this.form.dep)
            this.onSubmit()
        },
        methods: {
            /**
             * 初始数据获取
             */
            initData () {
                this.orgList = this.getLocalStorage('userInfo', 'mechanism')
                // 因为orgId是必选的，所以依靠这个来判断是否有页面独立的搜索条件
                let query = this.$store.state.search.searchForm[this.$route.name]
                if (query.orgId) {
                    this.form = {
                        orgId: query.orgId,
                        dep: this.setDepId(query.orgId, query.department, query.depName),
                        timeUnit: query.timeUnit,
                        yearMonth: query.yearMonth,
                        quarter: query.quarter
                    }
                    this.globalForm = {
                        orgId: query.orgId,
                        department: query.department,
                        depName: query.depName,
                        start: query.start,
                        end: query.end
                    }
                    // 判断是否有保存的最新筛选参数
                } else if (localStorage.getItem('globalSearchDRG')) {
                    this.form = JSON.parse(localStorage.getItem('globalSearchDRG'))
                    this.globalForm = JSON.parse(localStorage.getItem('globalFormDRG'))
                    // 保存当前页面参数(筛选参数和表单参数一起)
                    this.setGetStore(this.$route.name, this.form, this.globalForm)
                } else {
                    // 第一次进入
                    let date = new Date()
                    this.form.yearMonth = `${date.getFullYear()}-${date.getMonth() + 1}-01`
                    this.setMechanismId()
                }
            },
            /**
             * 查找科室id
             * @param orgId 机构id
             * @param depCode 科室类别
             * @param depName 科室名称
             */
            setDepId (orgId, depCode, depName) {
                if (!depCode) return ''
                let res = ''
                let orgList = this.getLocalStorage('userInfo', 'mechanism')
                orgList.forEach(item => {
                    if (item.id === orgId && item.organDep && item.organDep.length && !res) {
                        res = this.findDepId(item.organDep, depCode)
                    }
                })
                return res
            },
            /**
             * 查找科室id
             * @param list 科室列表
             * @param code 科室类别
             * @param name 科室名称
             */
            findDepId (list, code, name) {
                let res = ''
                list.forEach(item => {
                    if ((item.code === code || item.code.split('.')[0] === code) && item.name === name) {
                        res = item.id
                    } else if (item.children && item.children.length && !res) {
                        res = this.findDepId(item.children, code)
                    }
                })
                return res
            },
            /**
             * 设置机构id
             */
            setMechanismId () {
                if (this.orgList.length) {
                    if (this.getLocalStorage('userMechanism', 'id') && this.hasMechanismId(this.getLocalStorage('userMechanism', 'id'))) {
                        this.form.orgId = this.getLocalStorage('userMechanism', 'id')
                    } else {
                        this.form.orgId = this.orgList[0].id
                    }
                }
            },
            /**
             * 判断所属机构是否在组织机构中
             * @param id 所属机构id
             */
            hasMechanismId (id) {
                let res = this.orgList.filter(item => item.id === id)
                return res.length !== 0
            },
            /**
             * 选择年
             * @param data 选择的数据
             */
            selectYear (data) {
                this.form.yearMonth = data
            },
            /**
             * 选择机构后设置出院科室内容
             * @param val 选中的id
             * @param department 科室id
             */
            setDepartmentList (val, department) {
                this.isResouceShow++
                this.form.dep = ''
                this.departmentList = []
                let checkAuth = Number(this.getLocalStorage('userInfo', 'checkAuth'))
                let index = this.orgList.findIndex(item => item.id === val)
                let departmentList = []
                if (this.orgList.length) {
                    departmentList = this.orgList[index].organDep
                    this.viewDeadlineDays = this.orgList[index].viewDeadlineDays
                    if (departmentList.length && checkAuth !== 1 && checkAuth !== 2 && departmentList[0].id !== '0') {
                        departmentList.unshift({
                            id: '0',
                            name: '全院'
                        })
                    }
                }
                this.departmentList = departmentList
                // 判断的是'' 和 undefined
                if (department) {
                    this.form.dep = department
                } else if (departmentList.length && (checkAuth === 1 || checkAuth === 2)) {
                    this.form.dep = departmentList[0].id
                } else {
                    this.form.dep = departmentList.length ? '0' : ''
                }
                if (this.$route.query.department && this.form.dep === '0') {
                    this.form.dep = ''
                }
            },
            /**
             * 获取对应科室
             * @param arr 科室集合
             * @param id 查询的科室id
             */
            getDepCode (arr, id) {
                let res = []
                if (arr && !res.length) {
                    arr.forEach(item => {
                        if (item.id === id && !res.length) {
                            res.push(item)
                        } else if (item.children && !res.length) {
                            res = this.getDepCode(item.children, id)
                        }
                    })
                }
                return res
            },
            onSubmit () {
                this.globalForm.orgId = this.form.orgId
                // 判断是否有科室选中
                if (this.form.dep === '' || this.form.dep === '0') {
                    this.globalForm.department = ''
                    this.globalForm.depName = ''
                } else {
                    let depItem = this.getDepCode(this.departmentList, this.form.dep)
                    this.globalForm.department = depItem[0] ? depItem[0].code : ''
                    this.globalForm.depName = depItem[0] ? depItem[0].name : ''
                }
                // 获取对应时间选择器时间
                this.globalForm = this.getPickerTime(this.globalForm)
                // 保存当前页面参数(筛选参数和表单参数一起)
                this.setGetStore(this.$route.name, this.form, this.globalForm)
                if (this.form.dep !== '' && this.departmentList.length) {
                    this.$router.push({query: {}})
                }
                // 保存最新筛选参数
                if (this.$route.meta && !this.$route.meta.independent) {
                    localStorage.setItem('globalSearchDRG', JSON.stringify(this.form))
                    localStorage.setItem('globalFormDRG', JSON.stringify(this.globalForm))
                    localStorage.setItem('viewDeadlineDays', this.viewDeadlineDays)
                }
                this.$emit('submitSearch', this.globalForm)
            },
            /**
             * 获取时间
             * @param params 参数对象
             */
            getPickerTime (params) {
                let time = this.form.yearMonth
                let timeArr = time.split('-')
                let year = timeArr[0]
                let month = timeArr[1]
                // 每月天数
                let d = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
                if (this.form.timeUnit === 'month') {
                    params.start = time
                    // 判断闰年二月
                    if (parseInt(month) === 2 && year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
                        params.end = `${year}-${month}-${d[parseInt(month) - 1] + 1}`
                    } else {
                        params.end = `${year}-${month}-${d[parseInt(month) - 1]}`
                    }
                } else if (this.form.timeUnit === 'quarter') {
                    // 判断季度
                    switch (this.form.quarter) {
                    case '1':
                        params.start = `${year}-01-01`
                        params.end = `${year}-03-31`
                        break
                    case '2':
                        params.start = `${year}-04-01`
                        params.end = `${year}-06-30`
                        break
                    case '3':
                        params.start = `${year}-07-01`
                        params.end = `${year}-09-30`
                        break
                    case '4':
                        params.start = `${year}-10-01`
                        params.end = `${year}-12-31`
                        break
                    }
                } else if (this.form.timeUnit === 'year') {
                    params.start = `${year}-01-01`
                    params.end = `${year}-12-31`
                }
                return params
            }
        },
        components: {SelectYear}
    }
</script>

<style scoped lang="scss">
    .global-search-container {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        padding-top: 3px;
        .el-form-item {
            margin-bottom: 10px;
        }
        .mechanism {
            width: 120px;
        }
        .dep-select {
            width: 120px;
        }
        .time-unit {
            width: 75px;
        }
        /deep/.year-month {
            width: 120px;
        }
        .quarter {
            width: 100px;
        }
        .tool-box {
            button {
                padding: 0;
                height: 28px;
                line-height: 28px;
                font-size: 14px;
            }
        }
        .time-select-form-box {
            /deep/.el-form-item__content {
                height: 29px;
                & > div {
                    float: left;
                }
            }
        }
    }
</style>
